/*
 * @Author: '浪川' '1214391613@qq.com'
 * @Date: 2025-07-02 11:37:26
 * @LastEditors: '浪川' '1214391613@qq.com'
 * @LastEditTime: 2025-07-08 14:37:44
 * @FilePath: \passiflora-edulis-sims\src\utils\proxyData.ts
 * @Description: 实现 LeaferJS 的响应化
 *
 * Copyright (c) 2025 by '1214391613@qq.com', All Rights Reserved.
 */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { shallowReactive, watch } from 'vue'

import { UI, defineKey } from 'leafer-ui'

// 定义proxyData

defineKey(UI.prototype, 'proxyData', {
  get() {
    return this.__proxyData
      ? this.__proxyData
      : (this.__proxyData = this.createProxyData())
  },
})

// 设置元素属性时，内部同步设置代理数据

UI.prototype.setProxyAttr = function (name: string, newValue: unknown): void {
  const data = this.__proxyData as any
  if (data[name] !== newValue) data[name] = newValue
}

// 获取元素属性时，内部优先返回代理数据

UI.prototype.getProxyAttr = function (name: string): any {
  const value = (this.__proxyData as any)[name]
  return value === undefined ? this.__.__get(name) : value
}

// 创建响应式数据

UI.prototype.createProxyData = function () {
  // 1.获取所有样式数据(含默认值)
  const data = this.__.__getData()

  // 2. 生成响应式数据
  const proxyData = shallowReactive(data)

  // 3.观察响应式数据变化，同步更新元素数据
  for (const name in data) {
    watch(
      () => proxyData[name], // source
      (newValue) => {
        if (this.__.__get(name) !== newValue) (this as any)[name] = newValue
      } // callback
    )
  }

  return proxyData
}
